<script setup lang="ts">
import { computed, ref, unref, watch } from 'vue'
import { ElMessage, UploadProps, ElInput, ElUpload, ElButton } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { propTypes } from '@/utils/propTypes'
import { PATH_URL } from '@/axios/service'
import { getFileName } from '@/utils'

const userStore = useUserStore()

const emit = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: propTypes.string.def(''),
  limitSize: propTypes.number.def(0),
  fileTypes: propTypes.array.def([]),
  uploadText: propTypes.string.def('选择附件'),
  disabled: propTypes.bool.def(false),
  preview: propTypes.bool.def(true)
})

watch(
  () => props.modelValue,
  (val: string) => {
    if (val === unref(valueRef)) return
    valueRef.value = val
  }
)

// 输入框的值
const valueRef = ref(props.modelValue)
const value = computed(() => (valueRef.value ? getFileName(valueRef.value) : ''))

// 监听
watch(
  () => valueRef.value,
  (val: string) => {
    emit('update:modelValue', val)
  }
)

const handleBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (props.fileTypes.length > 0) {
    const isFileType = props.fileTypes.includes(rawFile.type)
    if (!isFileType) {
      ElMessage.error('上传文件不符合格式: ' + props.fileTypes)
    }
  }
  if (props.limitSize && props.limitSize > 0) {
    const isLtSize = rawFile.size / 1024 / 1024 < props.limitSize
    if (!isLtSize) {
      ElMessage.error(`上传文件大小不能超过 ${props.limitSize} MB!`)
    }
    return isLtSize
  }
}
// 上传成功的钩子函数
const handleUploadSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.code === 200) {
    valueRef.value = response.data.remote_path.startsWith('http')
      ? response.data.remote_path
      : PATH_URL + response.data.remote_path
  } else {
    ElMessage.error(response.message)
  }
}
</script>

<template>
  <ElInput v-model="valueRef" :disabled="props.disabled" clearable :value="value">
    <template #prepend>
      <ElUpload
        :action="`${PATH_URL}/upload/file`"
        :data="{ path: 'attchements' }"
        :show-file-list="false"
        :before-upload="handleBeforeUpload"
        :on-success="handleUploadSuccess"
        :disabled="props.disabled"
      >
        <ElButton>{{ uploadText }}</ElButton>
      </ElUpload>
    </template>
    <template #append v-if="props.preview && valueRef">
      <a :href="valueRef" target="_blank">预览</a>
    </template>
  </ElInput>
</template>
